﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework;

namespace SunRayEngine.MapEditor.EditTools
{
    public class MapGrid
    {
        #region fields
        private int width;
        private int height;
        public MapTile[,] Tiles;
        private Point[] tilesOnScreen;
        #endregion

        #region properties
        public Point[] TilesOnScreen { get { return tilesOnScreen; } }
        #endregion

        #region initialization
        public MapGrid(int offsetX, int offsetY, int width, int height, GraphicsDevice device, Rectangle bounds)
        {
            this.width = width;
            this.height = height;
            Tiles = new MapTile[width, height];

            for (int x = 0; x < width; x++)
                for (int y = 0; y < height; y++)
                    Tiles[x, y] = new MapTile(offsetX + (x * 32), offsetY + (y * 32), 32, 32, device);

            UpdateTilesOnScreen(bounds);
        }
        #endregion

        #region methods
        public void EditOffset(Point p)
        {
            for (int x = 0; x < width; x++)
                for (int y = 0; y < height; y++)
                    Tiles[y, x].EditOffset(p);
        }

        public void Draw(SpriteBatch spriteBatch, Rectangle bounds)
        {
            foreach(var p in tilesOnScreen)
                        Tiles[p.Y, p.X].Draw(spriteBatch);
        }

        public void UpdateTilesOnScreen(Rectangle bounds)
        {
            List<Point> points = new List<Point>();

            for (int x = 0; x < width; x++)
                for (int y = 0; y < height; y++)
                    if (Tiles[y, x].Bounds.Intersects(bounds))
                        points.Add(new Point(x, y));

            tilesOnScreen = points.ToArray();
        }
        #endregion
    }
}
